package com.example.searchcenter.article;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.searchcenter.R;
import com.example.searchcenter.helper.AlertDialogManager;
import com.example.searchcenter.helper.ConnectionDetector;
import com.example.searchcenter.helper.JSONParser;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("NewApi")
public class NewsFragment extends Fragment {
	
	ListView list_article;
	TextView ver;
	TextView name;
	TextView thumbnail;
	View rootView;

	// Connection Detector
	ConnectionDetector cd;
	
	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Hashmap articlelist
	ArrayList<HashMap<String, String>> articlelist = new ArrayList<HashMap<String,String>>();
	
	// URL get Json
	private static String url = "http://tinhnguyen.edu.vn/apis/getAllArticle";
	private static String url_image = "https://tinhnguyen.edu.vn/public/img/articles/thumbs/";
	public static final String TAG_ARTICLES = "article";
	public static final String TAG_ID_ARTICLE = "cid";
	public static final String TAG_DATE = "date";
	public static final String TAG_TITLE = "title";
	public static final String TAG_CATEGORYID = "categoryid";
	public static final String TAG_TITLEASCII = "titleASCII";
	public static final String TAG_AUTHORID = "postedUserId";
	public static final String TAG_TAG = "tag";
	public static final String TAG_SUMARY = "sumary";
	public static final String TAG_DETAILS = "details";
	public static final String TAG_SOURCE = "source";
	public static final String TAG_THUMBNAILIMAGEURL = "thumbnailImageUrl";
	public static final String TAG_COUNT_ARTICLES = "count_articles";
	
	JSONArray arrArticle = null;
	NewsAdapter articleadapter;
	public NewsFragment(){}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        rootView = inflater.inflate(R.layout.fragment_news, container, false);
        
        new ListNews().execute();
        return rootView;
    }
	
	// get count articles
	public static String getCounterArticles()
	{
		JSONParser jParser = new JSONParser();
		// Getting JSON from URL
		JSONObject json = jParser.getJSONFromUrl(url);
		String counter = null;
		try{
			counter = json.getString(TAG_COUNT_ARTICLES);
		}
		catch(JSONException e){
			e.printStackTrace();
		}
		return counter;
	}
	
	private class ListNews extends AsyncTask<String, String, JSONObject> {
    	private ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Getting Data ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected JSONObject doInBackground(String... args) {
			JSONParser jParser = new JSONParser();
			// Getting JSON from URL
			JSONObject json = jParser.getJSONFromUrl(url);
			//Toast.makeText(getApplicationContext(),json.toString(), Toast.LENGTH_LONG).show();
			return json;
		}
	
		@Override
		protected void onPostExecute(JSONObject json) {
			pDialog.dismiss();
			
			try{
				arrArticle = json.getJSONArray(TAG_ARTICLES);
				
				for(int i = 0; i < arrArticle.length(); i++)
				{
					JSONObject c = arrArticle.getJSONObject(i);
					String cid = c.getString(TAG_ID_ARTICLE);
					String date = c.getString(TAG_DATE);
					String title = c.getString(TAG_TITLE);
					String categoryid = c.getString(TAG_CATEGORYID);
					String titleASCII = c.getString(TAG_TITLEASCII);
					String authorId = c.getString(TAG_AUTHORID);
					String tag = c.getString(TAG_TAG);
					String sumary = c.getString(TAG_SUMARY);
					String details = c.getString(TAG_DETAILS);
					String source = c.getString(TAG_SOURCE);
					String thumbnail = url_image+c.getString(TAG_THUMBNAILIMAGEURL);
					
					// Adding value HashMap key => value
					HashMap<String, String> hash_article = new HashMap<String, String>();
					hash_article.put(TAG_ID_ARTICLE, cid);
					hash_article.put(TAG_DATE, date);
					hash_article.put(TAG_TITLE, title);
					hash_article.put(TAG_CATEGORYID, categoryid);
					hash_article.put(TAG_TITLEASCII, titleASCII);
					hash_article.put(TAG_AUTHORID, authorId);
					hash_article.put(TAG_TAG, tag);
					hash_article.put(TAG_SUMARY, sumary);
					hash_article.put(TAG_DETAILS, details);
					hash_article.put(TAG_SOURCE, source);
					hash_article.put(TAG_THUMBNAILIMAGEURL, thumbnail);
					
					articlelist.add(hash_article);
					
					list_article = (ListView) rootView.findViewById(R.id.list_article);
					
					articleadapter = new NewsAdapter(getActivity(), articlelist);
					list_article.setAdapter(articleadapter);
					
					// Click go to detail article
					list_article.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							// getting values from selected ListItem
							String id_article = ((TextView) view
									.findViewById(R.id.id_article))
									.getText().toString();
							
							// Starting new intent
							Intent in = new Intent(getActivity(), DetailArticle.class );
							
							// sending pid to next activity
							in.putExtra(TAG_ID_ARTICLE, id_article);
							// starting new activity and expecting some response
							// back
							startActivityForResult(in, 100);
							
							/*Toast.makeText(
									News.this,
									"Bạn đã chọn  "
											+ articlelist.get(+position).get(
													"name") ,
									Toast.LENGTH_SHORT).show();*/
						}
					});
					
				}
			}
			catch(JSONException e){
				e.printStackTrace();
			}
		}
    }
}
